package bysun.weather;

import bysun.weather.http.HTTPRequester;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

/**
 * 天气信息读取
 */
public class WeatherReader {
    /**
     * 获取即时天气信息
     * @param code 地区编号
     * @return 天气信息
     * @throws IOException
     */
    public static WeatherLastHour getLastHour(String code) throws IOException {
        WeatherLastHour result = get(WeatherLastHour.class, code, Commons.get("weather.url.lasthour", Commons.URL_LAST_HOUR));

        return result;
    }

    /**
     * 获取六日天气信息
     * @param code 地区编号
     * @return
     * @throws IOException
     */
    public static WeatherSixDay getSixDay(String code) throws IOException {
        WeatherSixDay result = get(WeatherSixDay.class, code, Commons.get("weather.url.sixday", Commons.URL_LAST_HOUR));
        return result;
    }

    /**
     * 获取当日天气信息
     * @param code 地区编号
     * @return
     * @throws IOException
     */
    public static WeatherToday getToday(String code) throws IOException {
        WeatherToday result = get(WeatherToday.class, code, Commons.get("weather.url.today", Commons.URL_LAST_HOUR));

        return result;
    }


    private static <T> T get(Class<T> clz, String code, String url) throws IOException {
        url = url.replaceAll("(.*?)\\$\\{code\\}(.*)", "$1" + code + "$2");
        ObjectMapper mapper = new ObjectMapper();
        String json = HTTPRequester.get(url);
        json = json.replaceAll("^\\{\".+?\":(.+?\\})\\}$", "$1").toLowerCase();
        return mapper.readValue(json, clz);
    }

    public static void main(String[] args) {

        try {
            WeatherLastHour lastHour = WeatherReader.getLastHour("1010200");
            WeatherSixDay sixDay = WeatherReader.getSixDay("1010200");
            WeatherToday today = WeatherReader.getToday("1010200");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
